Functional programming is a programming paradigm that revolves around pure functions.
A pure function is a function which can be represented as a mathematical expression. That means, no side-effects should be present, i.e. no I/O operations, no global state changes, no database interactions.
The output from a pure function is depended ONLY on its inputs. Thus, if a pure function is called with the same inputs a million times, you would get the same result every single time.
In [1]:
# not so functional function
a = 0
def global_sum(x):
global a
x += a
return x
print(global_sum(1))
print(a)
a = 11
print(global_sum(1))
print(a)
In [4]:
# not so functional function
a = 0
def global_sum(x):
global a
return x + a
print(global_sum(x=1))
print(a)
a = 11
print(global_sum(x=1))
print(a)
In the above example, the output of the function global_sum
changed due to the value of a
, thus it is unfunctional function.
In [5]:
# a better functional function
def better_sum(a, x):
return a+x
num = better_sum(1, 1)
print(num)
num = better_sum(1, 3)
print(num)
num = better_sum(1, 1)
print(num)
and in the above example better_sum
, the function returns always the same value for the set of input and only provided input can have any impact on the output of the function.